﻿using PLM.ConfigurationCenter.Model;
using PLM.ConfigurationCenter.SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLM.ConfigurationCenter.Handler {
    /// <summary>
    /// 
    /// </summary>
    public class LogHandler {

        private readonly UIRichTextBox richTextBox;

        public LogHandler(UIRichTextBox richTextBox) {
            this.richTextBox = richTextBox;
        }
        /// <summary>
        /// 
        /// </summary>
        public void WriteLog(string level, string info) {
            var model = new LogInfoModel {
                Info = info,
                Level = level
            };
            DbManager.DbContext.Insertable(model).ExecuteCommand();
            richTextBox.BeginInvoke(new Action(() => {
                string[] strLines = richTextBox.Text.Split('\n');
                if (strLines.Length > 1000) {
                    richTextBox.Clear();
                }
                if (!string.IsNullOrEmpty(model.Info)) {
                    //让文本框获取焦点  
                    richTextBox.Focus();
                    //设置光标的位置到文本尾  
                    richTextBox.Select(richTextBox.TextLength, 0);
                    //滚动到控件光标处  
                    richTextBox.ScrollToCaret();
                    //更改颜色
                    if (model.Level == "警告") {
                        richTextBox.SelectionColor = Color.FromArgb(51, 255, 102);
                    } else if (model.Level == "错误") {
                        richTextBox.SelectionColor = Color.Red;
                    } else {
                        richTextBox.SelectionColor = Color.White;
                    }
                    richTextBox.AppendText($"{model.DateTime}：【{model.Level}】{model.Info}\r\n");
                }
            }));
        }

    }
}
